package cn.redragon.soa.common.util;

import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;

/**
 * @Author: Steven HUANG
 * @Date: 2019/12/10
 */
@Slf4j
public class DigestUtil {

    /**
     * 参数按字典排序，参数使用key=value组装，并在组装后的参数字符串前后加上encodingAesKey得到待签名字符串，signature不参与签名;
     * 使用sha256数字摘要算法生成签名值
     *
     * @param map        签名消息体
     * @param secret     签名的密钥
     * @param ignoreKeys 不参与签名的参数key, 比如：signature
     */
    public static String makeSign(Map<String, String> map, String secret, String... ignoreKeys) {
        if (MapUtils.isEmpty(map)) {
            throw new IllegalArgumentException("Sign params must not be null");
        }

        try {
            Set<String> ignoreSet = Set.of(ignoreKeys);
            Map<String, String> fieldMap = new TreeMap<>(map);

            StringBuffer buffer = new StringBuffer();
            buffer.append(secret);
            fieldMap.entrySet().stream()
                .filter(entry -> !ignoreSet.contains(entry.getKey()))
                .filter(entry -> StringUtils.isNotBlank(entry.getValue()))
                .forEach(entry -> buffer.append(entry.getKey()).append("=").append(entry.getValue()));
            buffer.append(secret);

            String signature = DigestUtils.sha256Hex(buffer.toString());
            log.debug("Valid system signature: {}, param: {}", signature, map);
            return signature;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new IllegalArgumentException("Make sign error");
        }

    }
}
